package com.ciwong.epaper.modules.pigai.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.LswScoreResult;
import com.ciwong.epaper.modules.epaper.bean.NewWorkScoreEvent;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.dao.LswDao;
import com.ciwong.epaper.modules.evaluate.bean.EssayAnswer;
import com.ciwong.epaper.modules.evaluate.bean.EssayResult;
import com.ciwong.epaper.modules.pigai.util.PigaiJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;

/**
 * 作文批改识别结果界面
 *
 * @author paul
 * @version ciwong v.1.0 2024/11/14 09:10
 * @since ciwong v.1.0
 */
public class NewPigaiRecoginzeResultActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_word_written;
    private LinearLayout ll_submit_pigai_written;
    private EssayResult essayResult;
    private LswScoreResult mLswScoreResult;
    private String answer;
    private int count = 1;
    private Handler handler = new Handler() {
    };

    @Override
    protected int setView() {
        return R.layout.activity_pigai_written_text_result;
    }

    @Override
    protected void findViews() {
        et_word_written = findViewById(R.id.et_word_written);
        ll_submit_pigai_written = findViewById(R.id.ll_submit_pigai_written);
    }

    @Override
    protected void initEvent() {
        ll_submit_pigai_written.setOnClickListener(this);
        showRightBtn();
        setRightBtnBG(R.mipmap.iv_camera_reset);
        setRightBtnEnable(true);
        setRightBtnListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                showReTakePhoteDialog();
            }
        });
    }

    @Override
    protected void init() {
        setTitleText("修改结果");
        Intent intent = getIntent();
        answer = intent.getStringExtra(IntentFlag.INTENT_FLAG_ANSWER);
        if (answer != null) {
            et_word_written.setText(answer);
        }
        count = 1;
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void loadData() {
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_submit_pigai_written) {
            // 提交批改结果
            showConfirmSubitmDialog();
        }
    }

    private CWDialog showTakePhotoDialog;

    /**
     * 返回拍照提示框
     */
    private boolean showReTakePhoteDialog() {
        if (showTakePhotoDialog == null) {
            showTakePhotoDialog = new CWDialog(this);
            showTakePhotoDialog.setTitle(R.string.get_permiss_title);
            showTakePhotoDialog.setTitleTextColor(Color.BLACK);
            showTakePhotoDialog.setMessage("识别新的作文，原来的作文会被覆盖", 16, Color.BLACK, Gravity.LEFT);
            showTakePhotoDialog.setPositiveButton(R.string.go_see_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    showTakePhotoDialog.dismiss();
                    setResult(RESULT_OK);
                    finish();
                }
            });
            showTakePhotoDialog.setNegativeButton(R.string.go_canel_no, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    showTakePhotoDialog.dismiss();
                }
            });
        }
        showTakePhotoDialog.show();
        return true;
    }

    private CWDialog showConfirmSubitmDialog;

    /**
     * 提交二次确认
     */
    private boolean showConfirmSubitmDialog() {
        if (showConfirmSubitmDialog == null) {
            showConfirmSubitmDialog = new CWDialog(this);
            showConfirmSubitmDialog.setTitle(R.string.get_permiss_title);
            showConfirmSubitmDialog.setTitleTextColor(Color.BLACK);
            showConfirmSubitmDialog.setMessage("拍照识别只是辅助输入功能，请认真检查文本后在提交", 16, Color.BLACK, Gravity.LEFT);
            showConfirmSubitmDialog.setPositiveButton(R.string.go_confirm_no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    showConfirmSubitmDialog.dismiss();
                    count = 1;
                    //提交测评
                    submitEssay();
                }
            });
            showConfirmSubitmDialog.setNegativeButton(R.string.go_check_ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    showConfirmSubitmDialog.dismiss();
                }
            });
        }
        showConfirmSubitmDialog.show();
        return true;
    }

    /**
     * 提交作文批改
     */
    public void submitEssay() {
        showCricleProgress("正在评分中...");
        int userId = (int) EApplication.getInstance().getUserInfoBase().getUserId();
        String userName = EApplication.getInstance().getUserInfoBase().getNickName();
        int classId = 0;
        if (EApplication.getInstance().getClazz() != null) {
            classId = (int) EApplication.getInstance().getClazz().getClassId();
        }
        EssayAnswer newDKAnswer = new EssayAnswer();
        newDKAnswer.setClassId(classId);
        newDKAnswer.setContent(et_word_written.getText().toString());
        newDKAnswer.setUserId(userId);
        newDKAnswer.setUserName(userName);

        EpaperDao.getInstance().submitEssayWork(newDKAnswer, new BaseExtCallBack(NewPigaiRecoginzeResultActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                super.failed(errorCode, data);
                failed(data);
            }

            @Override
            public void failed(Object data) {
                if (data instanceof TimeoutError) {
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterError("提交失败，请稍后再试");
                }
            }

            @Override
            public void success(Object data) {
                essayResult = (EssayResult) data;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getEssayScoreResult(essayResult.getDoWorkId());
                    }
                }, 1000);
            }
        });
    }

    private void getEssayScoreResult(String doworkId) {
        LswDao.getInstance().getEssayScoreResult(doworkId, new BaseCallBack() {
            @Override
            public void success(Object data) {
                super.success(data);
                mLswScoreResult = (LswScoreResult) data;
                if (null != mLswScoreResult) {
                    if (mLswScoreResult.getStatus() == 1) {
                        //评分成功
                        hideCricleProgress();
                        //跳转作文记录详情
//                        EventBus.getDefault().post();

                        EventBus.getDefault().post(new NewWorkScoreEvent(essayResult.getDoWorkId(),et_word_written.getText().toString(),mLswScoreResult.getScore()));
//                        PigaiJumpManager.jumpToEssayRecordDetailH5Activity(NewPigaiRecoginzeResultActivity.this, R.string.go_back, "", essayResult.getDoWorkId());
                        finish();
                    } else if (mLswScoreResult.getStatus() == 16) {
                        //评分中 继续获取
                        count++;
                        if (count < 8) {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    getEssayScoreResult(essayResult.getDoWorkId());
                                }
                            }, 2000);

                        } else {
                            hideCricleProgress();
                            showToastText("评分超时");
                        }
                    }
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                failed(data);
            }

            @Override
            public void failed(Object data) {
                CWLog.d(TAG, "###########获取评分失败############");
                if (data != null) {
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, data.toString(), "听说模考获取分数失败" + getUrl());
                }
                hideCricleProgress();
            }
        });
    }

    private void showToastText(final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToastError("评分超时");
            }
        });
    }

}
